//
//  UserViewController.m
//  chanyou
//
//  Created by leon on 15/1/7.
//  Copyright (c) 2015年 wanli. All rights reserved.
//

#import "UserViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "UIImage+Blur.h"
#import "UIImageView+WebCache.h"
#import "Singleton.h"
#import "CollectionTripsViewController.h"
#import "CollectionArticlesViewController.h"
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)



@interface UserViewController ()<UIScrollViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    BOOL isFullScreen;
    //下拉菜单
    UIActionSheet *myActionSheet;
    
    UIActionSheet *sexActionSheet;
    
    //图片2进制路径
    NSString* _filePath;
    
}
@end

@implementation UserViewController
- (void)dealloc
{
    [_userImgView release];

    [_nickName release];
    [_profileImage release];
    [_buttonBackgroudImgView release];
    [_headScrollView release];
    [_bigScrollView release];
    [_buttonList release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.nickName = @"";
        self.profileImage = @"";
        self.buttonList = [NSArray array];
    }
    return self;
}

- (void)logoutButtonClickHandler:(UIButton *)button
{
    [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
    Singleton *share = [Singleton shareInstance];
    share.logined = NO;
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:@"" forKey:@"user"];
    
    share.loginDefault = [NSUserDefaults standardUserDefaults];
    [share.loginDefault setObject:@"no" forKey:@"登陆状态"];
    
//    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//    // 注销之后要将此处清除
//    [def setObject:@"" forKey:@"user"];
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销" style:UIBarButtonItemStylePlain
                                                                    target:self
                                                                              action:@selector(logoutButtonClickHandler:)]autorelease];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.textColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"我的";
    self.navigationItem.titleView = label;
    [label release];
    
    [self createView];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
    //    [[SDImageCache sharedImageCache] clearMemory];
}


- (void)createView
{
    // 头部
    UIImageView *headImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 3 / 9)];
    UIImage *headerBackgroud = [UIImage imageNamed:@"user-header-view.jpg"];
    UIImage *headerBac = [headerBackgroud blurredImage:0.5];
    headImgView.image = headerBac;
    
    // 头像
    self.userImgView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2.45, SCREEN_WIDTH / 7.5, SCREEN_WIDTH / 6, SCREEN_WIDTH / 6)];
    
    [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        if (result) {
            self.profileImage = [userInfo profileImage];
//            NSUserDefaults *userImgView = [NSUserDefaults standardUserDefaults];
//            [userImgView setObject:_profileImage forKey:@"selfie"];
            
            [_userImgView sd_setImageWithURL:[NSURL URLWithString:_profileImage] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            
            // userNameLabel
            UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 3, SCREEN_WIDTH, SCREEN_WIDTH / 16)];
            userNameLabel.textAlignment = NSTextAlignmentCenter;
            userNameLabel.text = [userInfo nickname];
            userNameLabel.font = [UIFont systemFontOfSize:15];
            userNameLabel.font = [UIFont boldSystemFontOfSize:16];
//            [userNameLabel setTintColor:[UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1]];
//            [userNameLabel setTextColor:[UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1]];
            [userNameLabel setTextColor:[UIColor whiteColor]];
            
            [self.view addSubview:userNameLabel];

        }
    }];
    
//    [_userImgView sd_setImageWithURL:[NSURL URLWithString:[userImgView objectForKey:@"selfie"]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    _userImgView.layer.cornerRadius = SCREEN_WIDTH / 12;
    _userImgView.layer.masksToBounds = YES;
    [headImgView addSubview:_userImgView];

        //    // 改变头像
//    UIButton *changePhotoButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2.75, SCREEN_WIDTH / 3, SCREEN_WIDTH / 4, SCREEN_WIDTH / 16)];
//    [changePhotoButton setTitle:@"更改头像" forState:UIControlStateNormal];
//    changePhotoButton.alpha = 0.5;
////    changePhotoButton settitlt
//    changePhotoButton.backgroundColor = [UIColor lightGrayColor];
//    [changePhotoButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
//    changePhotoButton.layer.cornerRadius = SCREEN_WIDTH / 32;
//    [changePhotoButton addTarget:self action:@selector(changePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // bigScroll
    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 3 / 9, self.view.frame.size.width, self.view.frame.size.height * 7 / 9)];
    _bigScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height);
    _bigScrollView.pagingEnabled = YES;
    _bigScrollView.bounces = NO;
    _bigScrollView.scrollsToTop = YES;
    _bigScrollView.scrollEnabled = NO;
    _bigScrollView.delegate = self;
    [self.view addSubview:_bigScrollView];
    
    // viewController
    CollectionTripsViewController *firstViewController = [[CollectionTripsViewController alloc] init];
    firstViewController.view.frame = CGRectMake(0, self.view.frame.size.height / 15, self.view.frame.size.width, self.view.frame.size.height * 7 / 9);
    [_bigScrollView addSubview:firstViewController.view];
    [self addChildViewController:firstViewController];
    [firstViewController release];
    
    CollectionArticlesViewController *secondViewController = [[CollectionArticlesViewController alloc] init];
    secondViewController.view.frame = CGRectMake(self.view.frame.size.width,  self.view.frame.size.height / 15, self.view.frame.size.width, self.view.frame.size.height * 7 / 9);
    [_bigScrollView addSubview:secondViewController.view];
    [self addChildViewController:secondViewController];
    [secondViewController release];
    
    // scroll
    self.headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 3 / 9, self.view.frame.size.width, self.view.frame.size.height / 15)];
    _headScrollView.scrollEnabled = NO;
    _headScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headScrollView];
    
    // buttonBackImg
    self.buttonBackgroudImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, self.view.frame.size.height / 15)];
    _buttonBackgroudImgView.image = [UIImage imageNamed:@"head.png"];
    [_headScrollView addSubview:_buttonBackgroudImgView];
    
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, self.view.frame.size.height / 15)];
    [button1 setTitle:@"游记收藏" forState:UIControlStateNormal];
    [button1 setTintColor:[UIColor greenColor]];
    [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, self.view.frame.size.height / 15)];
    [button2 setTitle:@"专题收藏" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(buttonAction2:) forControlEvents:UIControlEventTouchUpInside];
    
    self.buttonList = [NSArray arrayWithObjects:button1, button2, nil];
    [self.view addSubview:headImgView];
    [self.view addSubview:_headScrollView];
//    [self.view addSubview:changePhotoButton];
    [_headScrollView addSubview:button1];
    [_headScrollView addSubview:button2];
    [headImgView release];
    
}

#pragma mark -
#pragma mark 相机及系统相册
- (void)changePhotoAction:(UIButton *)button
{
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"照相机", @"相册",nil];
    
    [myActionSheet showInView:self.view];
    [myActionSheet release];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet == myActionSheet) {
        //呼出的菜单按钮点击后的响应
        if (buttonIndex == myActionSheet.cancelButtonIndex)
        {
            NSLog(@"取消");
        }
        
        switch (buttonIndex)
        {
            case 0:  //打开照相机拍照
                [self takePhoto];
                break;
                
            case 1:  //打开本地相册
                [self LocalPhoto];
                break;
        }
        
    }
    
}

-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentModalViewController:picker animated:YES];
    
    [picker release];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        _filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];

        self.userImgView.image = image;
        
#pragma mark saveUserImg
        // 保存图像
        NSUserDefaults *userImgView = [NSUserDefaults standardUserDefaults];
        [userImgView setObject:_filePath forKey:@"selfie"];
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissModalViewControllerAnimated:YES];
}



-(void)sendInfo
{
    NSLog(@"图片的路径是：%@", _filePath);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)buttonAction1:(UIButton *)button
{
    _bigScrollView.contentOffset = CGPointMake(0, 0);
    _buttonBackgroudImgView.frame = CGRectMake(0, 0, self.view.frame.size.width / 2, self.view.frame.size.height / 15);
    for (UIButton *button in _buttonList) {
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
- (void)buttonAction2:(UIButton *)button
{
    _bigScrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    _buttonBackgroudImgView.frame = CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2, self.view.frame.size.height / 15);
    for (UIButton *button in _buttonList) {
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
